package org.csu.mypetstore.persistence.impl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.csu.mypetstore.utils.JdbcUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDAO<T>{   //泛型指定具体类型
    private QueryRunner qr = new QueryRunner();

    //开发通用的dml方法
    public int update(String sql,Object... parameters){
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return qr.update(connection,sql,parameters);
        } catch (SQLException e) {
            return -1;
        }finally {
            JdbcUtils.close(connection);
        }
    }

    //返回多个对象（查询结果是多行），针对任意表
    public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters){
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return qr.query(connection,sql,new BeanListHandler<T>(clazz),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JdbcUtils.close(connection);
        }
    }

    //查询单行结果
    public <T>T querySingle(String sql,Class<T> clazz,Object... parameters){
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return qr.query(connection,sql,new BeanHandler<T>(clazz),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JdbcUtils.close(connection);
        }
    }

    //查询单行单列（单值）的方法
    public Object queryScalar(String sql,Object... parameters){
        Connection connection = null;
        try {
            connection = JdbcUtils.getConnection();
            return qr.query(connection,sql,new ScalarHandler(),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JdbcUtils.close(connection);
        }
    }
}
